"""
@file: main.py
@author: lingdubing
@time: 2024/10/31  14:11
@desc: 程序的入口
@character: utf-8
"""

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from config import settings
from app.core import event, router, exception
from app.core.log_midderware import LogRequestMiddleware

from fastapi.openapi.docs import (
    get_redoc_html,
    get_swagger_ui_html,
    get_swagger_ui_oauth2_redirect_html,
)

# application = FastAPI(
#     debug=settings.app_debug,
# )



##########################配置本地swagger#############################################
application = FastAPI(
    debug=settings.app_debug,
    docs_url=None,
    redoc_url=None
)

"""
自定义配置接口本地静态文档
"""

@application.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
    return get_swagger_ui_html(
        openapi_url=application.openapi_url,
        title=application.title + " - Swagger UI",
        oauth2_redirect_url=application.swagger_ui_oauth2_redirect_url,
        swagger_js_url="/resources/static/swagger_ui/swagger-ui-bundle.js",
        swagger_css_url="/resources/static/swagger_ui/swagger-ui.css",
    )

@application.get(application.swagger_ui_oauth2_redirect_url, include_in_schema=False)
async def swagger_ui_redirect():
    return get_swagger_ui_oauth2_redirect_html()

@application.get("/redoc", include_in_schema=False)
async def custom_redoc_html():
    return get_redoc_html(
        openapi_url=application.openapi_url,
        title=application.title + " - ReDoc",
        redoc_js_url="/resources/static/redoc_ui/redoc.standalone.js",
    )

###########################################################################

# 静态文件挂载
application.mount("/resources/static", StaticFiles(directory=settings.static_dir))

# 事件监听
application.add_event_handler("startup", event.startup(application))
application.add_event_handler("shutdown", event.stopping(application))

# 日志中间价
application.add_middleware(LogRequestMiddleware)

# 异常处理
exception.register_exception_handlers(application)

# 路由挂载
application.include_router(router.router)

app = application

